using System;
using System.IO;
using System.Text;
using BSDS.Core.Data.Local;

namespace BSDS.Core.Model.Services.Uploading.DataProviders
{
    public class CsvDataDataProvider : DataProviderBase, IDataProvider
    {
        private readonly string filePath;
        private readonly string entityTypeName;

        public CsvDataDataProvider(string filePath, string entityTypeName, DataFormat dataFormat)
            : base(dataFormat)
        {
            this.filePath = filePath;
            this.entityTypeName = entityTypeName;
        }

        public void Initialize()
        {
            var encoding = Encoding.UTF8;

            using (var streamReader = new StreamReader(filePath))
            {
                var headerLine = string.Format("Bing Spatial Data Services, 1.0, {0}\n", entityTypeName);
                byte[] buffer = encoding.GetBytes(headerLine);

                MemoryStream.Write(buffer, 0, buffer.Length);

                var schemaLine = streamReader.ReadLine();

                if (schemaLine != null)
                {

                    // NOTE: The following two lines would be consisten with documentation examples
                    //       here: http://msdn.microsoft.com/en-us/library/gg650600.aspx where you 
                    //       can see that primaryKey is preceeded by the chosen separator. However
                    //       testing has revealed that "," is always used before primaryKey. -- nh
                    // var separator = CsvType.Parse(Format.Value).Separator;
                    // schemaLine = schemaLine.Replace("@", separator.Value) + "\n";
                    schemaLine = schemaLine.Replace("@", ",") + "\n";
                    buffer = encoding.GetBytes(schemaLine);

                    MemoryStream.Write(buffer, 0, buffer.Length);
                }

                var line = streamReader.ReadLine();

                while (line != null)
                {
                    buffer = encoding.GetBytes(line + "\n");
                    MemoryStream.Write(buffer, 0, buffer.Length);

                    line = streamReader.ReadLine();
                }
            }
        }
    }
}